import React, { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { Button, Form, Input, message } from 'antd'
import style from './style.module.less'
import IconSvg from '@/components/IconSvg'
// import wangjiPassword from '@/assets/images/wangjiPassword.png'
import { validatorPhone, validatorCode } from '@/utils/formValidator'
import { forgerPassword, getVerifyCode } from '../login/service/service'
import { isNullData } from '@/utils'

export default () => {
  const pushRouter = useNavigate()

  const [form] = Form.useForm()

  const [countdown, setCountdown] = useState(60)
  const [isCounting, setIsCounting] = useState(false)

  useEffect(() => {
    localStorage.removeItem('token')
  }, [])

  useEffect(() => {
    let timer: any

    if (isCounting) {
      timer = setInterval(() => {
        setCountdown((prevCountdown) => prevCountdown - 1)
      }, 1000)
    }

    return () => {
      clearInterval(timer)
    }
  }, [isCounting])

  const handleCountdown = async () => {
    const { getFieldValue } = form
    const phones = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
    const phoneName = getFieldValue('phone')

    if (phoneName === undefined) {
      message.error('请输入手机号!')
      return
    }
    if (!phones.test(phoneName)) {
      message.error('请输入有效的手机号!')
      return
    }

    if (!isCounting) {
      setCountdown(60)
      setIsCounting(true)

      setTimeout(() => {
        setIsCounting(false)
      }, 60000)
    }
    const res = await getVerifyCode({ phone: getFieldValue('phone') })
    if (isNullData(res)) {
      message.success('发送成功')
    }
  }

  const onFinish = async (value: any) => {
    // console.log(value)
    const res = await forgerPassword(value)
    if (isNullData(res) && res.data.status) {
      message.success('重置成功')
      pushRouter('/user/login')
    } else {
      message.info(res.data.msg)
    }
  }

  const [password, setPassword] = useState({
    pasOne: '',
    pasTwo: '',
  })

  const getPasswordOne = (e: any) => {
    setPassword({
      ...password,
      pasOne: e.target.value,
    })
  }
  const getPasswordTwo = (e: any) => {
    setPassword({
      ...password,
      pasTwo: e.target.value,
    })
  }

  const validatorPasswordOne = (rule: object, value: string) => {
    if (!value) {
      return Promise.reject('密码不能为空!')
    }
    if (value.length < 6) {
      return Promise.reject('最少输入6位密码!')
    }
    return Promise.resolve()
  }

  const validatorPasswordTwo = (rule: object, value: string) => {
    if (!value) {
      return Promise.reject('密码不能为空!')
    }
    if (value.length < 6) {
      return Promise.reject('最少输入6位密码!')
    }
    if (value !== password.pasOne && password.pasOne) {
      return Promise.reject('两次输入的密码不一致!')
    }
    return Promise.resolve()
  }

  return (
    <div className={style.wangjiPassword}>
      <div className={style.top}>
        <div className={style.iconSvg}>
          <IconSvg
            name='gobackLogin'
            onClick={() => {
              pushRouter('/user/login')
            }}
          />
        </div>
        <div
          onClick={() => {
            pushRouter('/user/login')
          }}
          style={{ color: '#5684ff', marginLeft: 7 }}
        >
          返回登录页
        </div>
      </div>
      <div className={style.bottom}>
        <div className={style.center}>
          {/*  */}
          <div className={style.images}>
            {/* <img src={wangjiPassword} /> */}
            <IconSvg name='wangjimimale' />
          </div>
          {/*  */}
          <div className={style.formDataBox}>
            <div className={style.topx}>忘记密码</div>
            <div className={style.bottom}>
              <Form
                form={form}
                name='basic'
                labelCol={{ span: 5 }}
                wrapperCol={{ span: 16 }}
                initialValues={{ remember: true }}
                onFinish={onFinish}
                //   onFinishFailed={onFinishFailed}
                autoComplete='off'
              >
                <Form.Item name='phone' rules={[{ required: true, validator: validatorPhone }]}>
                  <Input
                    prefix={<IconSvg name='wangji1' />}
                    maxLength={11}
                    placeholder='请输入手机号'
                    style={{ width: 320 }}
                  />
                </Form.Item>

                <div className={style.neBtn}>
                  <Form.Item name='verifyCode' rules={[{ required: true, validator: validatorCode }]}>
                    <Input
                      prefix={<IconSvg name='wangji2' />}
                      maxLength={6}
                      placeholder='请输入验证码'
                      style={{ width: 204 }}
                    />
                  </Form.Item>
                  <div className={style.tnndBtn}>
                    <Button type='primary' onClick={handleCountdown} disabled={isCounting}>
                      {isCounting ? `${countdown}` : '获取验证码'}
                    </Button>
                  </div>
                </div>

                <Form.Item
                  name='newPassword'
                  rules={[{ required: true, validator: validatorPasswordOne }]}
                  dependencies={['surePassword']}
                >
                  <Input.Password
                    prefix={<IconSvg name='wangji3' />}
                    autoComplete='new-password'
                    onChange={getPasswordOne}
                    maxLength={10}
                    placeholder='至少6位密码，区分大小写'
                    style={{ width: 320 }}
                  />
                </Form.Item>

                <Form.Item
                  name='surePassword'
                  rules={[{ required: true, validator: validatorPasswordTwo }]}
                  dependencies={['newPassword']}
                >
                  <Input.Password
                    prefix={<IconSvg name='wangji4' />}
                    autoComplete='new-password'
                    onChange={getPasswordTwo}
                    maxLength={10}
                    placeholder='至少6位密码，区分大小写'
                    style={{ width: 320 }}
                  />
                </Form.Item>

                <Form.Item wrapperCol={{ offset: 0, span: 16 }}>
                  <Button style={{ width: 320, marginTop: 40 }} type='primary' htmlType='submit'>
                    重置密码
                  </Button>
                </Form.Item>
              </Form>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
